import $ from 'jquery'
import Cookies from 'js-cookie'
import {Notify} from 'vant'
import { removeToken } from '../util/auth'

var userProfile = {'baseurl': process.env.API_ROOT, 'title': '图谱学院'}

/**
 * HTTP异步请求
 * @param req
 */
export default {
  doAction: function (req) {
    if (!(req.hasOwnProperty('successMsg'))) {
      req['successMsg'] = {
        isshow: false,
        msg: ''
      }
    }
    if (typeof req.url === 'undefined') {
      return
    }
    if (typeof req.async === 'undefined') {
      req.async = true
    }
    // console.log(Cookies.get('token'))
    // console.log(document.cookie)
    if (req.type === 'GET') {
      $.ajax({
        type: 'GET',
        url: userProfile.baseurl + req.url,
        headers: {Authorization: 'Bearer ' + Cookies.get('token')},
        dataType: 'json',
        async: req.async,
        beforeSend: req.beforeSend,
        success: this.success(req),
        complete: req.complete,
        error: this.error(req)
      })
    } else if (req.type === 'POST') {
      $.ajax({
        type: 'POST',
        headers: {Authorization: 'Bearer ' + Cookies.get('token')},
        data: JSON.stringify(req.items),
        url: userProfile.baseurl + req.url,
        dataType: 'json',
        async: req.async,
        contentType: 'application/json',
        // contentType: 'application/x-www-form-urlencoded',
        success: this.success(req),
        error: this.error(req)
      })
    }
  },
  success: function (req) {
    return function (res) {
      if (res.code === 401) {
        Notify({
          message: '登录信息过期，请重新登录',
          duration: 1000
        })
        removeToken()
        setTimeout(() => {
          window.location.href = '/login'
        }, 1000)
      }
      req.successCallback(res)
    }
  },
  error: function (req) {
    return function (res) {
      var resData = res.responseJSON
      // console.log(resData);
      if (resData.code === 401) {
        Notify({
          message: '登录信息过期，请重新登录',
          duration: 1000
        })
        setTimeout(() => {
          window.location.href = '/login'
        }, 1000)
      } else {
        Notify({
          message: resData.msg,
          duration: 1000
        })
        req.errorCallback(resData)
      }
    }
  }
}
